package com.ihrm.system.service.Impl;

import com.ihrm.common.entity.Constants;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.RolePermission;
import com.ihrm.system.dao.PermissionDao;
import com.ihrm.system.dao.RolePermissionDao;
import com.ihrm.system.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public Integer insert(Permission permission) {
        permission.setId(new IdWorker().nextId() + "");
        return permissionDao.insert(permission);
    }

    @Override
    public Integer update(Permission permission) {
        return permissionDao.update(permission);
    }

    @Override
    public Set<Permission> findAll(Permission permission) {
        //typed等于0，获取菜单和按钮权限
        if(permission.getType() == 0) {
            Permission permission1 = new Permission();
            permission1.setType(1);
            Set<Permission> list1 = permissionDao.findAll(permission1);
            Permission permission2 = new Permission();
            permission2.setType(2);Set<Permission> list2 = permissionDao.findAll(permission2);
            list1.addAll(list2);
            return list1;
        }
        return permissionDao.findAll(permission);

    }

    @Override
    public Permission findById(String id) {
        return permissionDao.findById(id);
    }

    @Override
    public Integer del(String id) {
        //删除权限前判断是否分配给了角色
        List<RolePermission> list = rolePermissionDao.getBypermId(id);
        if(list.size() > 0) {
            throw new CommonException(Constants.FAIL_CODE, "有角色分配了该权限不能删除");
        }
        return permissionDao.del(id);
    }
}
